//
//  ZMUtil.swift
//  ZMBaseModule
//
//  Created by Rowling on 2020/5/25.
//  Copyright © 2020 Rowling. All rights reserved.
//

import UIKit
import RxSwift
import HandyJSON

class ZMUtil {
    /**快速创建button*/
    static func button(title : String? = nil , image : UIImage? = nil, font : UIFont = UIFont.systemFont(ofSize: 16),color : UIColor = UIColor.white) -> UIButton {
        let btn = UIButton()
        btn.setTitle(title, for: .normal)
        btn.setImage(image, for: .normal)
        btn.titleLabel?.font = font
        btn.sizeToFit()
        btn.setTitleColor(color, for: .normal)
        return btn
    }
    
    /**快速创建label*/
    static func label(title : String? = nil , color : UIColor = UIColor.black , font : UIFont = UIFont.systemFont(ofSize: 16)) -> UILabel {
        let label = UILabel()
        label.text = title
        label.textColor = color
        label.font = font
        label.sizeToFit()
        return label
    }
    
    /**快速创建ImageView*/
    static func imageView(imageName : String = "",image : UIImage? = nil ) -> UIImageView {
        let img = UIImageView()
        if image != nil {
            img.image = image
        } else {
            img.image = UIImage.init(named: imageName)
        }
        img.sizeToFit()
        return img
    }
    
    /**快速创建UIStackView*/
    static func stackView(axis : NSLayoutConstraint.Axis, spacing : CGFloat = 0) -> UIStackView {
        let s = UIStackView()
        s.axis = axis
        s.spacing = spacing
        return s
    }
    
    /**快速加载nib*/
    static func loadNibView<T:NSObject>(nibName : T.Type) -> T {
        let classStr = NSStringFromClass(nibName)
        if classStr.contains(".") , let realclassStr = classStr.components(separatedBy: ".").last {
            return Bundle.main.loadNibNamed(realclassStr, owner: nil, options: nil)?.first as! T
        }
        return Bundle.main.loadNibNamed(classStr, owner: nil, options: nil)?.first as! T
    }
    
    /**快速加载nib*/
    static func loadNibViewFullScreen<T:UIView>(nibName : T.Type) -> T {
        let v = loadNibView(nibName: nibName)
        v.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: SCREEN_H)
        return v
    }
    
    /// 加载Storyboard
    static func loadStoryboard(storyboardName: String, storyboardId: String) -> UIViewController {
        return UIStoryboard.init(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: storyboardId)
    }
    
    /**切对应角的圆角*/
    static func clipCircle(view : UIView, Corner : UIRectCorner , radius : CGFloat ) {
        view.layoutIfNeeded()
        let maskPath = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: Corner, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = view.bounds
        maskLayer.path = maskPath.cgPath;
        view.layer.mask = maskLayer;
        view.layoutSubViewsCallBack = { [weak view] in
            guard let view = view, let maskLayer = view.layer.mask as? CAShapeLayer else {return}
            maskLayer.frame = view.bounds
            maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: Corner, cornerRadii: CGSize(width: radius, height: radius)).cgPath
        }
    }

    /** json转model*/
    static func jsonToModel<T:HandyJSON>(type : T.Type ,array : [Any]) -> [T] {
        
        let a = JSONDeserializer<T>.deserializeModelArrayFrom(array: array)?.filter({ (m) -> Bool in
            return m != nil
        }).map({$0!})
        return a ?? [T]()
    }
    
    /** NSDecimalNumberHandler*/
    static func DecimalNumberHandler(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16) -> NSDecimalNumberHandler {
       return NSDecimalNumberHandler.init(roundingMode: roundingMode, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
    }
    
    static func dealResponse<T : HandyJSON>(resp : ResponseModel<[String : Any]>, key : String, type : T.Type) -> ResponseModel<[T]> {
        var r = ResponseModel<[T]>()
        r.code = resp.code
        r.message = resp.message
        if let d = resp.data, let arrayd = d[key] as? [[String : Any]] {
            r.data = [T].deserialize(from: arrayd)?.compactMap({$0})
        }
        return r
    }
    
    class func defalutBottomButton(title : String, font : UIFont, height : CGFloat) -> UIButton {
        return ZMUtil.button(title: title, font: font, color: .white).then({$0.layer.cornerRadius = height / 2;$0.backgroundColor = Style.mainColor})
    }
    
    static func fastBehavior<T>(value : T) -> BehaviorRelay<T> {
        return BehaviorRelay<T>(value: value)
    }
    
    static func fastNilBehavior<T>(type : T.Type) -> BehaviorRelay<T?> {
        return BehaviorRelay<T?>(value: nil)
    }
    
    @discardableResult
    static func listRequest<T : HandyJSON>(type : T.Type, api : ZMApiProvider, callBack: @escaping resp<[T]>) -> DataRequest?  {
        return ZMAPIManage<[String : Any]>().sendReqeust(method: api) { resp in
            var r = ResponseModel<[T]>()
            r.code = resp.code
            r.message = resp.message
            r.realResp = resp.data
            if let d = resp.data{
                if let arrayd = d["list"] as? [[String : Any]] {
                    r.data = [T].deserialize(from: arrayd)?.compactMap({$0})
                } else {
                    r.data = []
                }
            }
            callBack(r)
        }
    }
}


class DebounceTool {
    static let THIRDE_LOGIN = "THIRDE_LOGIN"
    
    static let shard = DebounceTool()
    private init(){}
    var cashe = [String : DebounceItem]()
    func debounce(_ id : String,_ interval : Double = 1) -> Bool{
        if let de = cashe[id] {
            if de.time + de.interval > Date().timeIntervalSince1970 {
//                print("过载中。。。\(id)")
                return false
            } else {
                cashe[id] = DebounceItem.init(time: Date().timeIntervalSince1970, interval: interval)
                return true
            }
        } else {
            cashe[id] = DebounceItem.init(time: Date().timeIntervalSince1970, interval: interval)
            return true
        }
    }
    
    struct DebounceItem {
        var time : Double
        var interval : Double
    }
}


class XMButton : UIView {
    let img = UIImageView()
    let titlelabel = UILabel()
    let stack = ZMUtil.stackView(axis: .horizontal)
    
    var tapBlock : (()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(frame: CGRect, imageLocation : Int, img : UIImage?) {
        super.init(frame: frame)
        self.img.image = img
        if imageLocation == 1 {
            stack.axis = .vertical
            stack.addArrangedSubview(self.img)
            stack.addArrangedSubview(titlelabel)
            stack.alignment = .center
        }
        
        addSubview(stack)
        stack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        let tap = UITapGestureRecognizer()
        addGestureRecognizer(tap)
        tap.addTarget(self, action: #selector(onTap))
    }
    
    @objc func onTap() {
        if let tapBlock = tapBlock {
            tapBlock()
        }
    }
  
    
}
